<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-row :gutter="20">
                <el-col :span="12" :offset="0">养宠交流贴管理</el-col>
            </el-row>
        </template>
        <!-- card body -->
        <div>
            <el-form inline>
                <el-form-item label="搜索条件"> 
                    <el-select v-model="searchType"  style="min-width: 80px;">
                        <el-option label="标题" value="title"></el-option>
                        <el-option label="内容" value="content"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="searchKeyword" placeholder="搜索" clearable @change="handleSearch" style="min-width: 40px;"></el-input>
                </el-form-item>                   
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="tieziList" v-loading="loading" style="width: 100%">
                <el-table-column fixed label="ID" prop="id" width="80"></el-table-column>
                <el-table-column label="标题" prop="title" width="180">
                    <template #default="scope">
                        <div>{{ scope.row.title }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="发送者" prop="username" width="120"></el-table-column>
                <el-table-column label="发送时间" prop="create_time" width="180"></el-table-column>
                <el-table-column label="点赞数" prop="like_num" width="100"></el-table-column>
                <el-table-column label="内容" prop="content">
                    <template #default="scope">
                        <div class="content-preview">{{ scope.row.content }}</div>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            
            <div class="pagination-container" style="margin-top: 20px; text-align: center;">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="total"
                    :page-size="pageSize"
                    :current-page="currentPage"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
    
        <!-- 编辑帖子对话框 -->
        <el-dialog title="编辑帖子" v-model="dialogVisible" width="50%">
            <el-form :model="editForm" label-width="80px" :rules="rules" ref="editFormRef">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="editForm.title"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input type="textarea" v-model="editForm.content" rows="6"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitEdit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>
    
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getTieziList, deleteTiezi, updateTiezi } from '@/api/tiezi'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据定义
const tieziList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const searchType = ref('title')
const searchKeyword = ref('')
const dialogVisible = ref(false)
const editFormRef = ref(null)

// 编辑表单
const editForm = reactive({
    id: '',
    title: '',
    content: ''
})

// 表单验证规则
const rules = {
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 1, max: 100, message: '标题长度在1-100个字符之间', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入内容', trigger: 'blur' },
        { min: 1, max: 1000, message: '内容长度在1-1000个字符之间', trigger: 'blur' }
    ]
}

// 获取帖子列表
const fetchTieziList = async () => {
    loading.value = true
    try {
        const params = {
            page: currentPage.value
        }
        
        if (searchKeyword.value) {
            if (searchType.value === 'title') {
                params.search_title = searchKeyword.value
            } else {
                params.search_content = searchKeyword.value
            }
        }
        
        console.log('发送请求参数:', params);
        const res = await getTieziList(params);
        console.log('获取到的响应:', res);
        
        // 修改这里的数据处理逻辑
        if (res && res.data && res.data.code === 200) {
            tieziList.value = res.data.data || [];
            total.value = res.data.total || 0;
            // console.log('处理后的帖子列表:', tieziList.value);
        } else {
            console.error('请求成功但返回错误:', res);
            ElMessage.error((res?.data?.message) || '获取帖子列表失败');
        }
    } catch (error) {
        console.error('获取帖子列表出错:', error);
        ElMessage.error('获取帖子列表失败: ' + (error.message || '未知错误'));
    } finally {
        loading.value = false;
    }
}

// 处理搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchTieziList()
}

// 重置搜索
const resetSearch = () => {
    searchType.value = 'title'
    searchKeyword.value = ''
    currentPage.value = 1
    fetchTieziList()
}

// 处理分页
const handlePageChange = (page) => {
    currentPage.value = page
    fetchTieziList()
}

// 处理编辑
const handleEdit = (row) => {
    editForm.id = row.id
    editForm.title = row.title
    editForm.content = row.content
    dialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
    if (!editFormRef.value) return
    
    editFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const res = await updateTiezi(editForm.id, {
                    title: editForm.title,
                    content: editForm.content
                })
                
                if (res && res.data && res.data.code === 200) {
                    ElMessage.success('更新帖子成功')
                    dialogVisible.value = false
                    fetchTieziList() // 刷新列表
                } else {
                    ElMessage.error((res?.data?.message) || '更新帖子失败')
                }
            } catch (error) {
                console.error('更新帖子出错:', error)
                ElMessage.error('更新帖子失败: ' + (error.message || '未知错误'))
            }
        } else {
            return false
        }
    })
}

// 处理删除
const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除标题为"${row.title}"的帖子吗？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const res = await deleteTiezi(row.id)
            if (res && res.data && res.data.code === 200) {
                ElMessage.success('删除帖子成功')
                fetchTieziList() // 刷新列表
            } else {
                ElMessage.error((res?.data?.message) || '删除帖子失败')
            }
        } catch (error) {
            console.error('删除帖子出错:', error)
            ElMessage.error('删除帖子失败: ' + (error.message || '未知错误'))
        }
    }).catch(() => {
        // 取消删除操作
    })
}

// 页面加载时获取数据
onMounted(() => {
    fetchTieziList()
})
</script>
    
<style scoped>
.content-preview {
    max-height: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}
</style>